
package com.wceManage.manage.controller;

import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wceManage.manage.util.UserUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wceManage.beans.SysRole;
import com.wceManage.beans.SysUser;
import com.wceManage.beans.page.PageList;
import com.wceManage.commons.CommonUtil;
import com.wceManage.commons.PwdUtils;
import com.wceManage.commons.enums.UserTypeEnum;
import com.wceManage.commons.util.StringUtil;
import com.wceManage.services.SysRoleService;
import com.wceManage.services.SysUserService;

@Controller
@RequestMapping("sysuser")
public class SysUserController extends BaseController {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleService sysRoleService;

	@ModelAttribute("sysUser")
	public SysUser get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return UserUtils.get(id);
		} else {
			return new SysUser();
		}
	}

	/**
	 * 查询列表
	 *
	 * @param sysUser
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "", "/", "list" })
	public String list(SysUser sysUser, HttpServletRequest request)
			throws InstantiationException, IllegalAccessException {

		request.setAttribute("sysUser", sysUser);
//		TestUtil.test();

		return "sys/sysuser/list";
	}

	/**
	 * 异步获取list资源
	 *
	 * @param pageList
	 * @param sysUser
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping("asynList")
	@ResponseBody
	public PageList asynList(PageList pageList, SysUser sysUser) {
		sysUser.setUserType(1);
		return sysUserService.queryPage(pageList, sysUser);
	}

	/**
	 * 新增修改
	 *
	 * @param sysUser
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = { "add", "edit" }, method = RequestMethod.GET)
	public String edit(SysUser sysUser, Model model) {

		if (sysUser.getUserId() == null || sysUser.getUserId() < 1l) { // add
			sysUser = new SysUser();
		} else {
			sysUser = sysUserService.queryById(sysUser.getUserId());
		}

		model.addAttribute("sysUser", sysUser);

		List<SysRole> rlist = new ArrayList<>();
		rlist.addAll(sysRoleService.queryList(new SysRole()));
		model.addAttribute("allRoles", rlist);

		return "sys/sysuser/edit";
	}

	/**
	 * 修改
	 *
	 * @param userId
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "modify", method = RequestMethod.GET)

	public String modify(Long userId, Model model) {

		SysUser sysUser = sysUserService.queryById(userId);

		model.addAttribute("sysUser", sysUser);
		
		//销售
		if(null!=sysUser.getSalesperson()){
			SysUser salesUser = sysUserService.queryById(sysUser.getSalesperson());
			model.addAttribute("salesUser", salesUser);
		}else{
			model.addAttribute("salesUser", null);
		}

		return "sys/sysuser/edit";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(SysUser sysUser) {
		 Map<String, Object> result = new HashMap<String, Object>();
		 
		Map<String, Object> map = CommonUtil.validPhone(sysUser.getAccount());
		if (Integer.parseInt(map.get("code").toString()) == -1) {
			 result.put("msg", "手机号格式不正确");
			 result.put("code", -1);
			 return result;
		}
			
		sysUser.setUpdateBy(UserUtils.getUser().getUserId());
		// 如果新密码为空，则不更换密码
		if (StringUtil.isNotBlank(sysUser.getPassword())) {
			if (sysUser.getSalt() == null || sysUser.getSalt().isEmpty()) {
				sysUser.setSalt(PwdUtils.getSalt());
			}
			sysUser.setPassword(PwdUtils.saltPwd(sysUser.getPassword(), sysUser.getSalt()));
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		/*List<SysRole> roleList = Lists.newArrayList();
		List<Long> roleIdList = sysUser.getRoleIdList();
		for (SysRole r : UserUtils.getRoleList()) {
			if (roleIdList.contains(r.getRoleId())) {
				roleList.add(r);
			}
		}*/
		SysUser sysUserParm =new SysUser();
		sysUserParm.setAccount(sysUser.getAccount());
		SysUser sysUserPo=sysUserService.queryUser(sysUserParm);

		//sysUser.setRoleList(roleList);
		sysUser.setPhone(sysUser.getAccount());
		if (sysUser.getUserId() == null) {
			
			if(null!=sysUserPo){
				 result.put("msg", "该手机号已存在用户");
				 result.put("code", -1);
				 return result;
			}
			sysUser.setUserType(UserTypeEnum.USER.getCode());
			sysUser.setParent(0L);
			sysUserService.add(sysUser);
		} else {
			if(null!=sysUserPo){
				if(sysUserPo.getUserId().longValue()!=sysUser.getUserId().longValue()){
					 result.put("msg", "该手机号已存在用户");
					 result.put("code", -1);
					 return result;
				}
			}
			sysUserService.update(sysUser);
			// 清除老的用户与角色关联
			sysUserService.deleteUserRole(sysUser);
		}
		// 保存用户与角色关联
		if (sysUser.getRoleList() != null && sysUser.getRoleList().size() > 0) {
			sysUserService.insertUserRole(sysUser);
		}

		/*UserUtils.clearCache(sysUser);
		// 清除当前用户缓存
		if (sysUser.getAccount().equals(UserUtils.getUser().getAccount())) {
			UserUtils.clearCache();
		}*/
		result.put("msg", "保存成功!");
		result.put("code", 1);
		return result;
	}

	@RequiresPermissions("sys:user:delete")
	@RequestMapping("delete")
	@ResponseBody
	public Object delete(Long id, HttpServletRequest request) {
		SysUser sysUser = new SysUser();
		sysUser.setUserId(id);
		sysUser.setUpdateBy(UserUtils.getUser().getUserId());
		sysUser.setStatus(1);
		int result = sysUserService.delete(sysUser);
		
		// TODO 成功失败结果页面
		return result;
	}

	@RequestMapping("detail")
	public String detail(Long id, HttpServletRequest request) {
		SysUser sysUser = sysUserService.queryById(id);

		request.setAttribute("sysUser", sysUser);
		
		//推荐人-
		if(null!=sysUser && null!=sysUser.getParent()){
			SysUser partnerUser=sysUserService.queryById(sysUser.getParent());
			if(null!=partnerUser){
				request.setAttribute("pName", partnerUser.getUsername()+"  "+partnerUser.getAccount());
			}
		}
       
		if(null!=sysUser && null!=sysUser.getSalesperson()){
			SysUser salerUser=sysUserService.queryById(sysUser.getSalesperson());
			if(null!=salerUser){
				request.setAttribute("salespersonName", salerUser.getUsername());
				request.setAttribute("salespersonPhone", salerUser.getAccount());
			}
		}


		Map<String,Object> rewardTicketCountMap = new HashMap<String,Object>();

		Map<String,Object> map = new HashMap<String,Object>();
		map.put("phone", sysUser.getAccount());

		return "sys/sysuser/detail";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping("thaw")
	@ResponseBody
	public Object thaw(Long id, HttpServletRequest request) {
		SysUser sysUser = new SysUser();
		sysUser.setUserId(id);
		sysUser.setUpdateBy(UserUtils.getUser().getUserId());
		sysUser.setStatus(0);
		int result = sysUserService.delete(sysUser);
		// TODO 成功失败结果页面
		return result;
	}

	/**
	 * 验证登录名是否有效
	 *
	 * @param oldAccount
	 * @param mobile
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkAccount", method = RequestMethod.POST)
	public Boolean checkAccount(String oldAccount, String mobile) {
		if (mobile != null && mobile.equals(oldAccount)) {
			return Boolean.TRUE;
		} else if (mobile != null && sysUserService.queryUserByAccount(mobile) == null) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
	
	@RequiresPermissions("sys:user:delete")
	@RequestMapping("deleteBy")
    @ResponseBody
    public Object deleteBy(Long id) {
        int result = sysUserService.deleteByPrimaryKey(id);
        return result;
    }
	
	
	/**
	 * 客户导出
	 *
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"download"}, method = RequestMethod.GET)
	@ResponseBody
	public void downloadToUser(SysUser sysUser,HttpServletResponse response) {
		sysUser.setUserType(1);
		List<SysUser> sysUserList = sysUserService.queryList(sysUser);
		
		SXSSFWorkbook wb=getHSSFWorkbook(sysUserList);
		//响应到客户端
	   try {
	      setResponseHeader(response, "用户数据.xlsx");
	      OutputStream os = response.getOutputStream();
	      wb.write(os);
	      os.flush();
	      os.close();
	     } catch (Exception e) {
	      e.printStackTrace();
	   }
	
	}
	 //发送响应流方法
    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
           
            fileName = new String(fileName.getBytes(),"ISO8859-1");

            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private  SXSSFWorkbook getHSSFWorkbook(List<SysUser> sysUserList){

        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
       SXSSFWorkbook  wb = new SXSSFWorkbook();
       

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        SXSSFSheet sheet = (SXSSFSheet) wb.createSheet("客户信息记录");
        sheet.setDefaultColumnWidth(20);

        
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        SXSSFRow row = (SXSSFRow) sheet.createRow(0);

        // 第四步，创建单元格，并设置值表头 设置表头居中
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框  
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框  
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框  
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框  

        //声明列对象
        SXSSFCell cell = null;
        
        String[] title={"用户编号","姓名","手机号码","地址","购买数量","购买金额","状态","注册时间"};

        //创建标题
        for(int i=0;i<title.length;i++){
            cell = (SXSSFCell) row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        

        //创建内容
        for(int i=0;i<sysUserList.size();i++){
        	row = (SXSSFRow) sheet.createRow(i + 1);
        	SysUser user=sysUserList.get(i);
        	SXSSFCell cell0 = (SXSSFCell) row.createCell(0);
        	SXSSFCell cell1 = (SXSSFCell) row.createCell(1);
        	SXSSFCell cell2 = (SXSSFCell) row.createCell(2);
        	SXSSFCell cell3 = (SXSSFCell) row.createCell(3);
        	SXSSFCell cell4 = (SXSSFCell) row.createCell(4);
        	SXSSFCell cell5 = (SXSSFCell) row.createCell(5);
        	SXSSFCell cell6 = (SXSSFCell) row.createCell(6);
        	SXSSFCell cell7 = (SXSSFCell) row.createCell(7);
        	
        	cell0.setCellStyle(style);cell1.setCellStyle(style);
        	cell2.setCellStyle(style);cell3.setCellStyle(style);
        	cell4.setCellStyle(style);cell5.setCellStyle(style);
        	cell6.setCellStyle(style);cell7.setCellStyle(style);
        	
        	cell0.setCellValue(user.getUserId());
        	cell1.setCellValue(user.getUsername());
        	cell2.setCellValue(user.getAccount());
        	cell3.setCellValue(user.getAddress());
        	cell4.setCellValue(user.getByCount());
        	cell5.setCellValue(user.getByPrice());
        	if(null!=user.getStatus() && user.getStatus()==0){
        		cell6.setCellValue("正常");
        	}else{
        		cell6.setCellValue("已冻结");
        	}
        	
        	cell7.setCellValue(format.format(user.getCreateDate()));
        }
        return wb;
    }

}
